import Permissions

class CommandNotFound(Exception):
  "This exception is raised if no command is found"
  pass

class Interpreter:
  "Interprets commands from user input"
  def __init__(self, commandTable, permTable):
    """
    Builds the interpretter class.
    commandTable should be a dictionary of registered functions
    """
    self.commandTable = commandTable
    self.permTable    = permTable
  
  def interpret(self,ch,inc):
    """
    Accepts an input string like 'look monster'. The first word is the command word. If there is a registered command
    called look, the interpreter will call that command and send the rest of the words as arguments (in a tuple)
    """
    parts = str(inc).split(' ')
    command = parts[0]
    args = parts[1:]
    if len(args) is 0:
      args = [""]
      
    print ch.name, '->', command, '(', args, ')'
    possible_commands = [c for c in self.commandTable if c.startswith(command)]
    possible_commands.sort()
    print possible_commands
    if command and possible_commands:
      command = possible_commands[0]
      cmd = self.commandTable[command] # cache the command
      if Permissions.isAuthorized(ch,command):
        cmd(ch,args)
      else:
        raise CommandNotFound
    else:
      raise CommandNotFound
      
  def abbrev(self,word):
    pass   

def force_command( ch, args ):
  """
  Syntax:
  force <player> <commands>
  
  Sends commands to the interpreter as player.
  """
  try:
    vict = ch.getPlayerInWorld(args[0])
  except:
    ch.toSelf("You must supply a victim")
    return
  
  if vict is None:
    ch.toSelf("Can't find %s." % args[0])
    return
  
  try:
    cmds = " ".join(args[1:])
  except:
    ch.toSelf("Force %s to do what?" % vict.name)
    return
  
  print "%s is forcing %s to |%s|" % (ch.name,vict.name,cmds)
  vict.interpret(cmds)
